package net.gdface.facelog.client.dtalk;

import gu.dtalk.engine.ItemEngineRedisImpl;
import gu.dtalk.engine.SampleConnector;
import gu.simplemq.ISubscriber;
import gu.simplemq.Channel;
import gu.simplemq.IMQConnParameterSupplier;
import gu.simplemq.IMessageQueueFactory;
import gu.simplemq.IPublisher;
import net.gdface.facelog.Token;
import net.gdface.utils.BinaryUtils;
import net.gdface.utils.NetworkUtil;

import static gu.dtalk.CommonUtils.*;
import static gu.dtalk.engine.DeviceUtils.DEVINFO_PROVIDER;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.base.Function;

import gu.dtalk.MenuItem;

/**
 * 基于dtalk的设备命令引擎
 * @author guyadong
 *
 */
public class DtalkEngineForFacelog {
	private final SampleConnector connAdapter;
	private final ISubscriber subscriber;
	private final byte[] devMac;
	private final ItemEngineRedisImpl itemAdapter;
	private final IMessageQueueFactory factory;
	public DtalkEngineForFacelog(MenuItem root, Function<Token,Integer>  ranker,IMessageQueueFactory factory) {
		this.factory = checkNotNull(factory,"factory is null");
		this.subscriber = factory.getSubscriber();
		devMac = DEVINFO_PROVIDER.getMac();
		IPublisher publisher = factory.getPublisher();
		itemAdapter = (ItemEngineRedisImpl) new ItemEngineRedisImpl(publisher).setRoot(root);
		connAdapter = new SampleConnector(publisher,subscriber)
				.setSelfMac(BinaryUtils.toHex(devMac))
				.setItemAdapter(itemAdapter);
		if(ranker != null){
			connAdapter.setRequestValidator(new TokenRequestValidator(ranker));
		}
	}

	public ItemEngineRedisImpl getItemAdapter() {
		return itemAdapter;
	}
	/**
	 * 启动连接
	 * @return 当前对象
	 */
	public DtalkEngineForFacelog start(){
		System.out.printf("DEVICE MAC address(设备地址): %s\n",NetworkUtil.formatMac(devMac, ":"));
		String connchname = getConnChannel(devMac);
		Channel<String> connch = new Channel<>(connchname, String.class)
				.setAdapter(connAdapter);
		subscriber.register(connch);
		System.out.printf("Connect channel registered(连接频道注册) : %s \n",connchname);
		return this;
	}

	/**
	 * 停止Dtalk引擎<br>
	 * 取消频道订阅不再接收频道消息
	 */
	public void stop(){
		// 取消所有订阅
		subscriber.unsubscribe((new String[0]));
	}
	/**
	 * @return 返回当前redis连接类型
	 */
	public IMQConnParameterSupplier getMessageQueueParameterSupplier() {
		return factory;
	}

	public IMessageQueueFactory getFactory() {
		return factory;
	}
}
